<?php

namespace wxApp;


use fast\Http;
use think\Cache;
use WeChatPay\Builder;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;
use WeChatPay\Util\PemUtil;

class WxApp
{

// 设置参数

    // 商户号
    private $appid = "wxde7c4c1de695c4ca";
    private $appsecret = "2e0707d731c4bfda0a7c65c3a3b13583";

    public function GetOpenid($code)
    {

        $queryarr = [
            "appid" => $this->appid,
            "secret" => $this->appsecret,
            "js_code" => $code,
            "grant_type" => "authorization_code",
        ];
        return Http::get("https://api.weixin.qq.com/sns/jscode2session", $queryarr);
    }

    public function getAccessToken()
    {


        $access_token = Cache::get("access_token");
        $expires_in = Cache::get("expires_in");

        if (!empty($access_token)) {
            if ((time()-$expires_in) < 5400) {
                return $access_token;
            }
        }

        $queryarr = [
            "appid" => $this->appid,
            "secret" => $this->appsecret,
            "grant_type" => "client_credential",
        ];

        $res = Http::get("https://api.weixin.qq.com/cgi-bin/token", $queryarr);
        $res = json_decode($res,true);
        Cache::set("access_token",$res["access_token"]);
        Cache::set("expires_in",time());

        return $res["access_token"];

    }

    //手机号
    public function getPhoneNumber($code,$openid)
    {

        $queryarr = [
            "code" => $code,
            "openid" => $openid,
        ];

        $res = Http::post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$this->getAccessToken(), json_encode($queryarr));

        return $res;

    }


    public function getWxacodeUnlimit($scene,$page) {
        //配置APPID、APPSECRET
        $APPID = $this->appid;
        $APPSECRET =  $this->appsecret;
       // $userId    =  $_GET['userId'];
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$APPSECRET}";

        //缓存access_token
        session_start();
        $_SESSION['access_token'] = "";
        $_SESSION['expires_in'] = 0;

        $ACCESS_TOKEN = "";
        if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
        {

            $json = $this->httpRequest( $access_token );
            $json = json_decode($json,true);
            $_SESSION['access_token'] = $json['access_token'];
            $_SESSION['expires_in'] = time()+7200;
            $ACCESS_TOKEN = $json["access_token"];
        }
        else{

            $ACCESS_TOKEN =  $_SESSION["access_token"];
        }

        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        //env_version 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$ACCESS_TOKEN}";


        $param = json_encode(array("scene"=>$scene,"page"=>$page,"check_path"=>false,"env_version"=>"trial","width"=> 150,"is_hyaline"=>false));

        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");

        //生成二维码
        // file_put_contents("qrcode.png", $result);
        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );

        // $this->result(0, '成功', ['qrcode'=>$base64_image,'wxName'=>$SystemSet['wxName']]);
        //把请求发送到微信服务器换取二维码

        return $base64_image;
    }
    function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }


    // 发送订阅消息
    public function sendMessage($template_id, $openid, $data_template)
    {
        $access_token = $this->getAccessToken();

        // 发送订阅消息的接口
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$access_token";
        // 需要发送的消息体
        $message_data = [
            "touser" => $openid,
            "template_id" => $template_id,
            "page" => "pages/index/index",
            "miniprogram_state" => "trial",
            "lang" => "zh_CN",
            "data" => $data_template
        ];
        // 初始化cURL
        $ch = curl_init();
        // 配置cURL
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => json_encode($message_data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json']
        ]);
        // 执行cURL
        $response = curl_exec($ch);
        // 判断发送结果
//        if (curl_errno($ch)) {
//            // 失败
//            echo '执行失败: ' . curl_error($ch);
//        } else {
//            // 成功
//            echo '执行成功: ' . $response;
//        }
        // 关闭cURL
//        halt($response);
        curl_close($ch);
//        echo $response;
    }


    // 文本内容安全识别
    public function msgSecCheck($content,$scene,$openid)
    {
        $access_token = $this->getAccessToken();

        // 发送订阅消息的接口
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=$access_token";
        // 需要发送的消息体
        $message_data = [
            "content" => $content,
            "version" => 2,
            "scene" => $scene,
            "openid" => $openid,
        ];

        $res = Http::post($url, json_encode($message_data));

        halt($res);
        return $res;
    }


}


